package com.itcast.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itcast.dao.UserDataMapper;
import com.itcast.health.pojo.PageResult;
import com.itcast.health.pojo.QueryPageBean;
import com.itcast.health.pojo.Role;
import com.itcast.health.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


import java.util.*;

/**
 * @author LiHaoPeng
 * @date 2019-12-03 11:45
 */
@Service(interfaceClass = UserDataService.class)
@Transactional
public class UserDataServiceImpl implements UserDataService {

    @Autowired
    private UserDataMapper userDataMapper;

    @Override
    public void add(User user) {
        String username = user.getUsername();
        //判断用户是否唯一
        if (null != username) {
            Integer userNameCount = userDataMapper.findCountByUserName(username);
            if (null != userNameCount && userNameCount > 0) {
                throw new RuntimeException();
            }
        }

        user.setBirthday(new Date());
        //保存用户基本信息并返回主键
        userDataMapper.add(user);
        Integer userId = user.getId();
        //获取要添加角色的Id
        Integer role = user.getRole();

        //把用户和角色关联起来
        setUserAndRolesRelation(userId, role);

    }

    private void setUserAndRolesRelation(Integer userId, Integer role) {
        //查询用户之前是否关联角色
        Integer relationCount = userDataMapper.findUserAndRolerRelationByUserId(userId);
        if (null != relationCount && relationCount > 0) {
            //如果用户存在关系就删除原来关系从新建立
            userDataMapper.deleteUserAndRolerRelationByUserId(userId);
        }
        //建立用户和角色的关系
        if (null != role) {
            //把所有参数交给数据
            Map map = new HashMap();
            map.put("user_id", userId);
            map.put("role_id", role);

            userDataMapper.setUserAndRoleRelationMap(map);
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //使用分页插件（Page page = PageHelper.startPage(当前页面，每页显示条数)）
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());

        Page page = (Page) userDataMapper.findPage(queryPageBean.getQueryString());

        List<User> result = page.getResult();
        for (User user : result) {
            Role role = userDataMapper.findRoleByUserId(user.getId());
            user.setRolename(role.getName());
        }
        return new PageResult(page.getTotal(), result);
    }

    @Override
    public void edit(User user) {
        //修改检查组的基本信息
        userDataMapper.edit(user);
        //建立新的关系
       setUserAndRolesRelation(user.getId(),user.getRole());
    }

    @Override
    public Set<Role> findRoles() {
        return userDataMapper.findRoles();
    }

    @Override
    public void delete(Integer id) {
        //删除原来的关系
        userDataMapper.deleteUserAndRolerRelationByUserId(id);
        //删除检查组
        userDataMapper.delete(id);
    }

    @Override
    public Map findById4Edit(Integer id) {
        // 1.1、根据用户的id查询角色的基本信息(t_user) , 赋值给formData （数据变化页面自定变化）
        User user = userDataMapper.findById(id);
        // 1.2.根据用户Id查询用户上次的角色
        Role role = userDataMapper.findRoleByUserId(id);

        Map map = new HashMap();
        map.put("user", user);
        map.put("role", role);

        return map;
    }
}
